<template>
  <div
    :class="isPhone ? 'common-layout mobile' : 'common-layout'"
    @click="handleBodyClick"
    ref="layoutRef"
  >
    <el-container>
      <el-aside :width="isCollapse ? (isPhone ? '0px' : '64px') : '200px'">
        <Aside :isCollapse="isCollapse" />
      </el-aside>
      <el-container class="main-container">
        <el-header style="border-bottom: 1px solid #ccc">
          <Header @asideCollapse="collapse" :isCollapse="isCollapse" />
        </el-header>
        <el-main>
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<script>
import Header from '@/views/admin/Header.vue'
import Aside from '@/views/admin/Aside.vue'
import { ref, onMounted, onUnmounted } from 'vue'
export default {
  components: {
    Header,
    Aside
  },
  setup() {
    const isCollapse = ref(false)
    const screenWidth = ref(document.documentElement.clientWidth)
    const isPhone = ref(screenWidth.value < 993) // 小于993视为平板及手机
    const layoutRef = ref(null)

    const handleBodyClick = (event) => {
      // 处理点击事件逻辑
      const target = event.target
      const sidebar = layoutRef.value
      if (
        isPhone.value &&
        !isCollapse.value &&
        sidebar &&
        !sidebar.contains(target)
      ) {
        isCollapse.value = true
      }
    }
    onMounted(() => {
      window.addEventListener('resize', () => {
        screenWidth.value = document.body.offsetWidth
        isPhone.value = document.body.offsetWidth < 993 // 小于993视为平板及手机
      })

      document.addEventListener('click', handleBodyClick)
    })

    onUnmounted(() => {
      document.removeEventListener('click', handleBodyClick)
    })

    return {
      isCollapse,
      isPhone,
      layoutRef
    }
  },
  methods: {
    collapse() {
      // 点击收缩按钮触发
      this.isCollapse = !this.isCollapse
    }
  }
}
</script>

<style lang="scss" scoped>
.common-layout {
  display: flex;
}

.common-layout .el-aside {
  height: 100%;
  box-shadow: 2px 0 6px rgba(0, 21, 41, 0.35);
  transition: width 0.28s;
}

.common-layout .main-container {
  flex: 1;
}

.mobile .el-aside {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  z-index: 1;
}
</style>
